package cn.zwx.remoting.netty;

import cn.zwx.constant.FeignRpcCommonConstant;
import cn.zwx.util.DefaultThreadFactory;
import cn.zwx.util.DelegatedScheduledExecutorServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;

import javax.annotation.Resource;
import java.util.Date;
import java.util.concurrent.*;

/**
 * NettyServer优先加载
 * @author 105286
 */
@Order(-Integer.MAX_VALUE)
public class NettyServerRunner implements CommandLineRunner {

    private static final Logger logger = LoggerFactory.getLogger(NettyServerRunner.class);

    @Resource
    private NettyRemotingServer server;


    private static ScheduledExecutorService executor = new DelegatedScheduledExecutorServiceImpl
            (new ScheduledThreadPoolExecutor(1,new DefaultThreadFactory("NettyServerRunner#startServer")));


    @Value("${server.port}")
    private int port;


    @Override
    public void run(String... args) {
        // init server
        server.start();
        // rebind
        startServer();
    }

    private void startServer() {
        //判断server是否正常如果不正常则再次绑定端口
        executor.scheduleWithFixedDelay(() -> {
                    if (!server.isActive()) {
                        server.bind(port + FeignRpcCommonConstant.STEP);
                    }
                }
                , 0, 5, TimeUnit.SECONDS);
    }
}
